package servlet;

import java.io.IOException;
import java.util.Date;

import org.bson.Document;
import org.bson.types.ObjectId;

import com.mongodb.client.MongoCursor;

import mongo.Task;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet(description = "teacherTaskServletProcess", urlPatterns = { "/teacher/task/taskServlet" })
public class teacherTaskServlet extends HttpServlet{
	private Task Task = new Task();
	HttpSession session = null;
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
	    response.setContentType("text/html;charset=UTF-8");
		
		String method = request.getParameter("method");
		if(method.equals("upload")){
			this.upload(request, response);
		}else if(method.equals("list")){
			this.list(request, response);
		}else{
//			request.getRequestDispatcher("404.jsp").forward(request, response); 添加错误页面
		}
	
	}

	
	public void upload(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
        try {
        	String uploadfilename = request.getParameter("uploadfilename");
        	String uploadfiledir = this.getServletContext().getRealPath("/upload") +"/"+ uploadfilename; //获取路径
        	ObjectId taskid = new ObjectId(request.getParameter("taskid"));
        	Document updateDocument = new Document("uploadfilename",uploadfilename).
        			append("uploadfiledir", uploadfiledir).append("isfinish", true);
    		Boolean result = Task.update(taskid,updateDocument);
    		if(result) {
    			this.list(request, response);
    		}

    	    //建议提示教师上传成功
        }catch(Exception e){
            System.err.println( e.getClass().getName() + ": " + e.getMessage() );
          //TODO发生异常,跳转到对应页面
        }

	}
	

	
	public void list(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		session = request.getSession();
		Document user = (Document)session.getAttribute("result");
		
        try {
    		MongoCursor<Document> result = Task.listByTeachercode(user.getString("username"));
    		request.setAttribute("result", result);
    	    request.getRequestDispatcher("taskList.jsp").forward(request, response);
    		//response.sendRedirect("departList.jsp");
    		//TODO针对所属模块，返回到相对应的页面   
        }catch(Exception e){
            System.err.println( e.getClass().getName() + ": " + e.getMessage() );
          //TODO发生异常,跳转到对应页面
        }

	}
	
}
